/**
 * This file is part of iSecurePasswords.
 *
 *   iSecurePasswords is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   iSecurePasswords is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with iSecurePasswords.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Author: Matthew MacGregor
 * Created: 2012
 * iSecurePasswords, copyright 2013 Sudolink, LLC
 * 
 */ 
package com.sudolink.isp.ui;

import com.sudolink.crypto.CryptoException;
import com.sudolink.cryptodata.CryptInfoBundle;
import com.sudolink.cryptodata.ISecureData;
import com.sudolink.io.IStore;
import com.sudolink.io.Store;
import com.sudolink.isp.app.Application;
import com.sudolink.isp.app.DesktopManager;
import com.sudolink.isp.media.ResourceConstants;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPasswordField;
import javax.swing.JToggleButton;
import org.apache.commons.codec.digest.DigestUtils;

public class EntryEditFormManager {
    
    /**
     * Toggles the password field between locked (read-only) and unlocked (editable).
     * 
     * @param btnPwLock Password lock button.
     * @param passwordField  Password field.
     */
    public void togglePasswordLockState( JToggleButton btnPwLock, JPasswordField passwordField )
    {
        //Abstract this!
        if ( btnPwLock.isSelected() )
        {
            passwordField.setEditable(true);
            btnPwLock.setIcon(new javax.swing.ImageIcon(getClass().getResource(ResourceConstants.LOCK_UNLOCK_ICON)));
        }
        else
        {
            passwordField.setEditable(false);
            btnPwLock.setIcon(new javax.swing.ImageIcon(getClass().getResource(ResourceConstants.LOCK_ICON)));
        }
    }
    
    /**
     * Launches the default browser with the given URL.
     * 
     * @param url URL to redirect.
     * @throws URISyntaxException If the url is badly-formed.
     * @throws IOException  Other IOExceptions.
     */
    public void launchBrowser( String url ) throws URISyntaxException, IOException
    {
        DesktopManager dm = new DesktopManager();
        URI uri = new URI(url);
        dm.browse(uri);
    }
    
    /**
     * Generate checksum.
     * @param inputs The string to hash.
     * @return The generated checksum.
     */
    public String generateChecksum( String inputs ) {
        return DigestUtils.shaHex(inputs);
    }
    
    /**
     * Check if two checksums match. Utility function to help readability.
     * 
     * @param x Checksum 1.
     * @param y Checksum 2.
     * @return True if the two strings are equal.
     */
    public boolean validateChecksums( String x, String y ) {
        return x.equals(y);
    }
    
    /**
     * Validation for the name entry field.
     * 
     * @param text The name.
     * @return True if the name is valid, else false.
     */
    public boolean validateEntryNameField( String text ) {
        boolean success = false;
        if ( text.length() > 0 ) {
            success = true;
        }
        return success;
    }
    
    /**
     * Helper method for saving the data for this element.
     * 
     * @param element The data element.
     * @param password The password.
     */
    protected void saveData( ISecureData element, char[] password ){
        CryptInfoBundle bundle = Application.getPrivateKeys();
        
        try {
            IStore store = new Store(Application.getPathToDatabase());
            store.shouldOverwrite(true);
            Application.getSecureDataManager().saveAll(store, bundle);
        } catch (IOException | CryptoException ex) {
            Logger.getLogger(EntryEditForm.class.getName()).log(Level.SEVERE, null, ex);
        }

        com.matsuzine.utils.HelperMethods.clearArray(password);

    }
    
    /**
     * Converts a timeframe in milliseconds to an index that is useable in the 
     * combobox for password reset reminder UI.
     */
    protected int convertMillisecondExpirationToIndex( long ms ) {
        long days = TimeUnit.MILLISECONDS.toDays(ms);
        if( days <= 30 ) {
            return 0;
        } else if ( days <= 90 ) {
            return 1;
        } else if ( days <= 120 ) {
            return 2;
        } else if ( days <= 180 ) {
            return 3;
        } else if ( days <= 365 ) {
            return 4;
        } else {
            return 1;
        }
    }
    
    /**
     * Converts an index to a timeframe in milliseconds. This is based on the 
     * UI combobox that allows a user to choose the password reset timeout for
     * an entry. 
     */
    protected long convertIndexToMillisecondExpiration( int index ) {
        int days = 90;
        switch( index ) {
            case 0:
                days = 30;
                break;
            case 1:
                days = 90;
                break;
            case 2:
                days = 120;
                break;
            case 3:
                days = 180;
                break;
            case 4:
                days = 365;
                break;
        }
        
        long ms = TimeUnit.DAYS.toMillis(days);
        return ms;
    }
    
    
}
